import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:pornhub_app/components/base_refresh/base_refresh_controller.dart';
import 'package:pornhub_app/components/base_refresh/base_refresh_page_counter.dart';
import 'package:pornhub_app/http/api/api.dart';
import 'package:pornhub_app/model/blogger/blogger_fans_model.dart';
import 'package:pornhub_app/services/user_service.dart';

class BloggerFansController extends BaseRefreshController
    with BaseRefreshPageCounter {
  final int userId;
  BloggerFansController(this.userId);
  final _pageSize = 20;
  bool isLoadedData = false;
  bool _requesting = false;
  List<BloggerFansModel> fansList = List<BloggerFansModel>.of([]);

  Future<bool> join(int groupId, int selectedIndex) async {
    final ass = Get.find<UserService>().assets.gold ?? 0;
    if (ass == 0) {
      SmartDialog.showToast('余额不足!', alignment: Alignment.center);
      return false;
    }
    final p = 38;
    if (ass < p) {
      SmartDialog.showToast('余额不足!', alignment: Alignment.center);
      return false;
    }
    if (_requesting) {
      return false;
    }
    _requesting = true;
    SmartDialog.showLoading(msg: "加入中...");

    final r = await Api.joinGroup(groupId, selectedIndex + 1);
    _requesting = false;
    SmartDialog.dismiss();
    if (r != null && r) {
      SmartDialog.showToast("加入成功!", alignment: Alignment.center);
      Get.find<UserService>().updateAPIAssetsInfo();
      return true;
    }
    return false;
  }

  @override
  Future<IndicatorResult> onRefresh() async {
    resetPage();

    List<BloggerFansModel>? resp = await Api.queryFansGroupUser(
        userId: userId, page: page, pageSize: _pageSize);
    isLoadedData = true;
    if (resp == null) {
      return IndicatorResult.fail;
    }
    incPage();
    _setList(resp);
    return IndicatorResult.success;
  }

  @override
  Future<IndicatorResult> onLoad() async {
    List<BloggerFansModel>? resp = await Api.queryFansGroupUser(
        userId: userId, page: page, pageSize: _pageSize);
    if (resp == null) {
      return IndicatorResult.fail;
    }

    _addList(resp);
    if (resp.length < _pageSize) {
      return IndicatorResult.noMore;
    }
    incPage();
    return IndicatorResult.success;
  }

  void _setList(List<BloggerFansModel>? list) {
    fansList.clear();
    _addList(list);
  }

  void _addList(List<BloggerFansModel>? list) {
    if (null != list && list.isNotEmpty) {
      fansList.addAll(list);
      update();
    }
  }
}
